(function ($) {
	AjaxSolr.AutocompleteWidget = AjaxSolr.AbstractFacetWidget.extend({
		init: function () {
			$(this.target).find('textarea').val('');

			var self = this;
			var area= $(this.target).find('textarea');

			var callback = function (response) {
				var list = [];
				for (var i = 0; i < self.fields.length; i++) {
					var field = self.fields[i];
					for (var facet in response.facet_counts.facet_fields[field]) {
						list.push({
							field: field,
							value: facet,
							text: facet + ' (' + response.facet_counts.facet_fields[field][facet] + ')'
						});
					}
				}

				self.requestSent = false;
				$(self.target).find('textarea').unautocomplete().autocomplete(list, {
					formatItem: function(facet) {
						return facet.value;
					},
					multiple: true 
				});
//				.result(function(e, facet) {
//					self.requestSent = true;
//					var value = facet.value;
//					self.manager.widgets["currentsearch"].requestInteractionsByProtein(value);
//				});

			}; // end callback
			$(this.target).find('button').click(function(e){
				var prots=area.val().split(",");
				var protsClean=[];
				for (var i=0; i<prots.length; i++){
					var prot=$.trim(prots[i]);
					if (prot!="")
						protsClean.push(prot);
				}
				for (var i=0; i<protsClean.length; i++){
					self.requestSent = true;
					if (typeof $(self.target).find('input').attr("checked") != 'undefined')
						self.manager.widgets["currentsearch"].requestInteractionsByProtein(protsClean[i]);
					else{
						var interactors= protsClean.slice(0,i).concat(protsClean.slice(i+1));
						self.manager.widgets["currentsearch"].requestSingleProtein(protsClean[i]);
						self.manager.widgets["currentsearch"].requestInteractionsBetweenProteins(protsClean[i],interactors);
							
					}
					//TODO: What if is just one protein... and/or none of the interactors list interacts with it??? Add Method AddSingleProtein!!!
				}
				$(self.target).find('textarea').val('');
			});
			var params = [ 'q=*:*&rows=0&facet=true&facet.limit=-1&facet.mincount=1&json.nl=map' ];
			for (var i = 0; i < this.fields.length; i++) {
				params.push('facet.field=' + this.fields[i]);
			}
			$.getJSON(this.manager.solrUrl + 'select/?' + params.join('&') + '&wt=json&json.wrf=?', {}, callback);
		}
	});
})(jQuery);